<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Controllers;

use App\Filters\GuestbookFilter;
use App\Http\Requests\GuestbookRequest;
use App\Http\Resources\GuestbookCollection;
use App\Models\Guestbook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 留言咨询模块
 * Class GuestbookController
 * @package App\Http\Controllers
 */
class GuestbookController extends Controller
{

    /**
     * 列表
     * @param GuestbookFilter $filter
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(GuestbookFilter $filter)
    {
        $paginate = Guestbook::filter($filter)->paginate($this->pageSize());
        $result = GuestbookCollection::make($paginate)->toArray(null);
        return $this->success('', $result);
    }

    /**
     * 删除
     * @param $id  // 1或者1,2
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {
            $between = explode(',', $id);
            Guestbook::destroy($between);
            DB::commit();
            return $this->successDestoryed();
        } catch (\Exception $e) {
            DB::rollback();
            return $this->exception($e->getMessage())->errorDestoryed();
        }
    }

    /**
     * 更新管理员备注
     * @param GuestbookRequest $request
     * @param Guestbook $guestbook
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Auth\Access\AuthorizationException
     * @throws \Illuminate\Validation\ValidationException
     */
    public function updateStatus(GuestbookRequest $request, Guestbook $guestbook)
    {
        $data = $request->validate('updateStatus');
        if($guestbook->status == 1) {
            return $this->error(__('guestbook.finished'));
        }
        $data['status'] = 1;
        if (!$guestbook->update($data)) return $this->error(__('guestbook.error_finish'));
        return $this->success(__('guestbook.success_finish'));
    }

}
